package com.quandou.base.security;

import com.quandou.base.security.entity.QdAuthority;
import com.quandou.base.security.service.QdAuthorityService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class UrlMetadataSource implements FilterInvocationSecurityMetadataSource {

    private QdAuthorityService qdAuthorityService;

    public UrlMetadataSource(QdAuthorityService qdAuthorityService) {
        this.qdAuthorityService = qdAuthorityService;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) {
        FilterInvocation invocation = (FilterInvocation) object;

        String method = invocation.getRequest().getMethod();
        String requestUrl = invocation.getRequest().getRequestURI();

        QdAuthority qdAuthority = qdAuthorityService.findByUrlAndMethod(requestUrl, method);
        if (null != qdAuthority)
            return SecurityConfig.createList(qdAuthority.getCode());

        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
